#!/bin/bash

### init sql
if [ ! `mysql -u ${MYSQL_USER_NAME} -p${MYSQL_USER_PASSWORD} -h${MYSQL_HOST} -e "show databases;"|grep "${MYSQL_DB}"` ];then
  mysql -u${MYSQL_USER_NAME} -p${MYSQL_USER_PASSWORD} -h${MYSQL_HOST} < ${AZKABAN_HOME}/azkaban-db/init.sql
fi

funStartExec(){
  ### start azkaban exec
  echo "start azkaban exec..."
  
  {
     funActivateExec
  }&

  cd ${AZKABAN_HOME}/azkaban-exec-server/;
  ./bin/internal/internal-start-executor.sh 2>&1 |tee -a executorServerLog__`date +%F+%T`.out
}

funStartWeb(){
  ### start azkaban web
  echo "start azkaban web..."
  cd ${AZKABAN_HOME}/azkaban-web-server/;
  ./bin/internal/internal-start-web.sh 2>&1 |tee -a webServerLog_`date +%F+%T`.out
}

funActivateExec(){
  until netstat -ntlp|grep -q :12321; do echo waiting for azkaban-exec; sleep 1; done
  curl -G "`hostname`:12321/executor?action=activate" && echo
}

if [ "$1" = "exec" ];then
   funStartExec
elif [ "$1" = "web" ];then
   funStartWeb
elif [ "$1" = "all" ];then
   funStartExec
   funStartWeb
else
   echo "please input args [exec|web|all]"
fi
